package com.example.module.custom.fragment;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import com.example.module.custom.R;
import com.example.module.custom.R2;
import com.example.module.custom.adapter.PatrolPageAdapter;
import com.example.module.custom.bean.PQCDetailsBean;
import com.example.module.custom.bean.PollingBean;
import com.example.module.custom.http.HTTPURL;
import com.example.module.custom.ui.PQCAddActivity;
import com.example.module.custom.utils.SoftKeyboardUtil;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.model.HttpParams;
import com.nand.library.base.base.BaseFragment;
import com.nand.library.base.bean.ResponseBean;
import com.nand.library.base.http.MyCallback;
import com.nand.library.base.http.OkGoUtils;


import java.util.ArrayList;
import java.util.List;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * @name BlockDemo
 * @class name：com.nand.module.function.fragment
 * @classdescribe 新增pqc检查项
 * @anthor ljp
 * @time 2020/1/7 10:55
 */
public class PQCTestFragment extends LazyBaseFragment {
    private static int FEATURES;//功能选项（1、新增pqc，2、复查pqc 3、查看详情【不可操作】）
    @BindView(R2.id.recycler_view_test)
    RecyclerView recyclerViewTest;
    @BindView(R2.id.btn_save)
    Button btnSave;
    private PatrolPageAdapter mRecyclerAdapter;
    private List<PQCDetailsBean.DetailListBean> pqcDetailsBeans;
    private String oid;
    private String TAG = "PQCTestFragment";
    /**
     * 标志位，标志已经初始化完成
     */
    private boolean isPrepared;
    /**
     * 是否已被加载过一次，第二次就不再去请求数据了
     */
    private boolean mHasLoadedOnce;
    private View view;
    private Context mContext;
    private static PQCTestFragment pqcTestFragment = null;
    public static PQCTestFragment getInstance() {
        if (pqcTestFragment == null) {
            synchronized (PQCTestFragment.class) {
                if (pqcTestFragment == null) {
                    pqcTestFragment = new PQCTestFragment();
                }
            }
        }
        return pqcTestFragment;
    }
    public static PQCTestFragment newInstance(int flag, String oid) {
        Bundle bundle = new Bundle();
        PQCTestFragment fragment = new PQCTestFragment();
        bundle.putInt("FEATURES", flag);
        bundle.putString("oid", oid);
        fragment.setArguments(bundle);
        pqcTestFragment = fragment;
        return fragment;
    }


    @Override
    public View initView() {
        view = View.inflate(getContext(), R.layout.fragment_pqc_test, null);
        ButterKnife.bind(this, view);
        FEATURES = getArguments().getInt("FEATURES");
        oid = getArguments().getString("oid");
        pqcDetailsBeans = new ArrayList<>();
        if (FEATURES == 1 || FEATURES == 2){
            btnSave.setVisibility(View.VISIBLE);
        }
        Log.i(TAG, "initView: ---FEATURES----" + FEATURES);
        recyclerViewTest.setLayoutManager(new LinearLayoutManager(mContext));
        mRecyclerAdapter = new PatrolPageAdapter(mContext,pqcDetailsBeans, R.layout.item_pqc_test, FEATURES);
        recyclerViewTest.setAdapter(mRecyclerAdapter);
        return null;
    }

    // 这里要特别注意，这个lazyLoad一定要重写，并且里面实现initData方法。
    //这里因为代码实现非常少，所以经常被人忽略，特此提醒
    @Override
    protected void lazyLoad() {
        initData();
    }
    /**
     *  @author ljp
     *  @time   18:59
     *  @describe 获得保存按钮
     */
    public Button getBtnSave() {
        return btnSave;
    }

    /**
     * 初始化数据的方法。 注意： 当请求网络成功以后，
     * 一定要将 mHasLoadedOnce 置为true ！！！
     */

    @Override
    public void initData() {
        if (!isPrepared || !isVisible || mHasLoadedOnce) {
            return;
        }
        featuresJud(); //发起网络请求的方法
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        initView();//初始化视图
        mContext = getActivity();
        // 页面初始化已经完成 变量置为true
        isPrepared = true;
        initData();
        ViewGroup parent = (ViewGroup) view.getParent();
        if (parent != null) {
            parent.removeView(view);
        }
        return view;
    }
    /**
     *  @author ljp
     *  @time   16:15
     *  @describe 清空原始数据 重新添加
     */
    public void clearOldData(){
        pqcDetailsBeans.clear();
        mRecyclerAdapter.getPqcList().clear();
        Log.i(TAG, "clearOldData: --pqcDetailsBeans-------"+pqcDetailsBeans.size());
        mRecyclerAdapter.setData(pqcDetailsBeans);
        mRecyclerAdapter.notifyDataSetChanged();
        //mHasLoadedOnce = false;
    }

    /**
     * @author ljp
     * @time 11:00
     * @describe 功能判断页面 //功能选项（1、新增pqc，2、复查pqc 3、查看详情【不可操作】）
     */
    private void featuresJud() {
        PQCDetailsBean pqcDetailsBeanTest;
        switch (FEATURES) {
            case 1:
                pqcDetailsBeanTest = PQCInforFragment.getPqcDetailsBeanTest();
                Log.i(TAG, "featuresJud: ------"+pqcDetailsBeanTest);
                if (pqcDetailsBeanTest != null)
                    selectHttpData(pqcDetailsBeanTest);
                break;
            case 2:
                setHttpData(HTTPURL.PQC_DETAILS);
                break;
            case 3:
                btnSave.setVisibility(View.GONE);
                setHttpData(HTTPURL.PQC_DETAILS);
                break;
        }
    }


    /**
     * @author ljp
     * @time 16:05
     * @describe 网络请求（查询检查内容）
     */
    private void selectHttpData(PQCDetailsBean pqcDetailsBean) {
        HttpParams httpParams = new HttpParams();
        httpParams.put("processOid", pqcDetailsBean.getProcessOid());
        httpParams.put("productionStage", pqcDetailsBean.getProductionStage());
        httpParams.put("materialOid", pqcDetailsBean.getMaterialOid());
        httpParams.put("checkType", pqcDetailsBean.getCheckType());
        OkGoUtils.getInstance().post(getActivity(), HTTPURL.PQC_ADD_CODE_SELECT_TEST, httpParams, 2, false, new MyCallback() {
            @Override
            public void onSuccess(ResponseBean response, int id) {
                //Log.i(TAG, "onSuccess: -----"+response.getCode());
                if (response.getCode() == 200) {
                    mHasLoadedOnce = true;
                    String data = response.getDataInfo().toString();
                    Log.i(TAG, "onSuccess: -----" + data);
                    pqcDetailsBeans = new Gson().fromJson(data, new TypeToken<List<PQCDetailsBean.DetailListBean>>() {
                    }.getType());
                    Log.i(TAG, "onSuccess: ---size----" + pqcDetailsBeans.size());
                    mRecyclerAdapter.setData(pqcDetailsBeans);
                }
            }

            @Override
            public void onError(Throwable e, int id) {

            }
        });

    }

    /**
     * @author ljp
     * @time 16:05
     * @describe 网络请求 (查询详情)
     */
    private void setHttpData(String url) {
        HttpParams httpParams = new HttpParams();
        httpParams.put("oid", oid);
        OkGoUtils.getInstance().post(getActivity(), url, httpParams, 1, true, new MyCallback() {
            @Override
            public void onSuccess(ResponseBean response, int id) {
                //Log.i(TAG, "onSuccess: -----"+response.getCode());
                if (response.getCode() == 200) {
                    mHasLoadedOnce = true;
                    String data = response.getDataInfo().toString();
                    //  Log.i(TAG, "onSuccess: -----"+response.getDataInfo().toString());
                    PQCDetailsBean pqcDetailsBean = new Gson().fromJson(data, PQCDetailsBean.class);
                    if (pqcDetailsBean.getDetailList() != null || !pqcDetailsBean.getDetailList().isEmpty()) {
                        mRecyclerAdapter.setData(pqcDetailsBean.getDetailList());
                    }
                }
            }

            @Override
            public void onError(Throwable e, int id) {

            }
        });

    }

    @OnClick(R2.id.btn_save)
    public void onViewClicked() {
        SoftKeyboardUtil.hideKeyboard(getActivity());
        List<PQCDetailsBean.DetailListBean> pqcList = mRecyclerAdapter.getPqcList();
        Gson gson2 = new Gson();
        String str = gson2.toJson(pqcList);
        Log.i(TAG, "onViewClicked: -------" + str);
        //((PQCAddActivity) getActivity()).setFragments(str, mRecyclerAdapter.isQualified());
    }


}
